<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.2/css/all.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"littlefxc.github.io","root":"/","images":"/images","scheme":"Mist","version":"8.2.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":false,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}};
  </script>
<meta name="description" content="负载均衡介绍将请求或者说流量，以期望的规则分摊到多个操作单元上进行执行。 通过它可以实现横向扩展(scale out)，将冗余的作用发挥为高可用。另外，还可以物尽其用，提升资源使用率。">
<meta property="og:type" content="article">
<meta property="og:title" content="Ribbon">
<meta property="og:url" content="http://littlefxc.github.io/2021/12/31/docs/%E5%BE%AE%E6%9C%8D%E5%8A%A1/Ribbon/index.html">
<meta property="og:site_name" content="一年春又来">
<meta property="og:description" content="负载均衡介绍将请求或者说流量，以期望的规则分摊到多个操作单元上进行执行。 通过它可以实现横向扩展(scale out)，将冗余的作用发挥为高可用。另外，还可以物尽其用，提升资源使用率。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/image-20211021155325000.png">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/image-20211021160108842.png">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/image-20211021160704789.png">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/5e12e23709f43f6528861210.png">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/5e12e63009550a2029541170.png">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/image-20220211103649256.png">
<meta property="article:published_time" content="2021-12-30T23:57:21.000Z">
<meta property="article:modified_time" content="2022-05-10T01:28:24.738Z">
<meta property="article:author" content="一年春又来">
<meta property="article:tag" content="ribbon">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/littlefxc/oss/raw/master/images/image-20211021155325000.png">


<link rel="canonical" href="http://littlefxc.github.io/2021/12/31/docs/%E5%BE%AE%E6%9C%8D%E5%8A%A1/Ribbon/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>
<title>Ribbon | 一年春又来</title>
  




  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="一年春又来" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">一年春又来</h1>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu">
        <li class="menu-item menu-item-home"><a href="/" rel="section"><i class="home                          //首页 fa-fw"></i>首页</a></li>
        <li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="archive          //归档 fa-fw"></i>归档</a></li>
        <li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="th           //分类 fa-fw"></i>分类</a></li>
        <li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="tags                     //标签 fa-fw"></i>标签</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E8%B4%9F%E8%BD%BD%E5%9D%87%E8%A1%A1%E4%BB%8B%E7%BB%8D"><span class="nav-text">负载均衡介绍</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%A6%82%E5%BF%B5"><span class="nav-text">概念</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%AE%A2%E6%88%B7%E7%AB%AF%E8%B4%9F%E8%BD%BD%E5%9D%87%E8%A1%A1"><span class="nav-text">客户端负载均衡</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%9C%8D%E5%8A%A1%E7%AB%AF%E8%B4%9F%E8%BD%BD%E5%9D%87%E8%A1%A1"><span class="nav-text">服务端负载均衡</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%8A%80%E6%9C%AF%E9%80%89%E5%9E%8B"><span class="nav-text">技术选型</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%B7%B1%E5%85%A5Ribbon"><span class="nav-text">深入Ribbon</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%B4%9F%E8%BD%BD%E5%9D%87%E8%A1%A1%E7%AD%96%E7%95%A5%E5%92%8C%E5%8E%9F%E7%90%86%EF%BC%8C%E5%8A%A0%E8%BD%BD%E6%96%B9%E5%BC%8F%EF%BC%8CIPing-%E6%9C%BA%E5%88%B6"><span class="nav-text">负载均衡策略和原理，加载方式，IPing 机制</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#LoadBalanced-%E5%8E%9F%E7%90%86%E8%A7%A3%E6%9E%90"><span class="nav-text">LoadBalanced 原理解析</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#LoadBalanced"><span class="nav-text">@LoadBalanced</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#LBAutoConfig"><span class="nav-text">LBAutoConfig</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%B4%9F%E8%BD%BD%E5%9D%87%E8%A1%A1%E7%AD%96%E7%95%A5%E4%BB%8B%E7%BB%8D"><span class="nav-text">负载均衡策略介绍</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E8%B4%9F%E8%BD%BD%E5%9D%87%E8%A1%A1%E7%AD%96%E7%95%A5%E9%85%8D%E7%BD%AE"><span class="nav-text">负载均衡策略配置</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Ribbon%E8%87%AA%E5%AE%9A%E4%B9%89%E5%9F%BA%E4%BA%8E%E5%93%88%E5%B8%8C%E4%B8%80%E8%87%B4%E6%80%A7%E8%B4%9F%E8%BD%BD%E5%9D%87%E8%A1%A1%E7%AD%96%E7%95%A5%E7%9A%84IRule"><span class="nav-text">Ribbon自定义基于哈希一致性负载均衡策略的IRule</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E4%B8%80%E8%87%B4%E6%80%A7%E5%93%88%E5%B8%8C%E7%AE%80%E5%8D%95%E4%BB%8B%E7%BB%8D"><span class="nav-text">一致性哈希简单介绍</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E8%87%AA%E5%AE%9A%E4%B9%89IRule%E5%AE%9E%E7%8E%B0"><span class="nav-text">自定义IRule实现</span></a></li></ol></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">一年春又来</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">234</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">38</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">125</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://littlefxc.github.io/2021/12/31/docs/%E5%BE%AE%E6%9C%8D%E5%8A%A1/Ribbon/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="一年春又来">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="一年春又来">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Ribbon
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2021-12-31 07:57:21" itemprop="dateCreated datePublished" datetime="2021-12-31T07:57:21+08:00">2021-12-31</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">更新于</span>
        <time title="修改时间：2022-05-10 09:28:24" itemprop="dateModified" datetime="2022-05-10T09:28:24+08:00">2022-05-10</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E5%88%86%E5%B8%83%E5%BC%8F%E7%B3%BB%E7%BB%9F/" itemprop="url" rel="index"><span itemprop="name">分布式系统</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h2 id="负载均衡介绍"><a href="#负载均衡介绍" class="headerlink" title="负载均衡介绍"></a>负载均衡介绍</h2><p>将请求或者说流量，以期望的规则分摊到多个操作单元上进行执行。</p>
<p>通过它可以实现横向扩展(scale out)，将冗余的作用发挥为高可用。另外，还可以物尽其用，提升资源使用率。</p>
<span id="more"></span>

<h2 id="概念"><a href="#概念" class="headerlink" title="概念"></a>概念</h2><h3 id="客户端负载均衡"><a href="#客户端负载均衡" class="headerlink" title="客户端负载均衡"></a>客户端负载均衡</h3><p><img src="https://gitee.com/littlefxc/oss/raw/master/images/image-20211021155325000.png" alt="image-20211021155325000"></p>
<p>基于客户端做负载均衡，有一个前提是需要在客户端本地维护一个服务的机器列表，同时在本地指定一个LB策略，然后输出一个服务。服务列表并不是一成不变的，机器列表需要通过注册中心动态更新机器列表。</p>
<h3 id="服务端负载均衡"><a href="#服务端负载均衡" class="headerlink" title="服务端负载均衡"></a>服务端负载均衡</h3><p><img src="https://gitee.com/littlefxc/oss/raw/master/images/image-20211021160108842.png" alt="image-20211021160108842"></p>
<ul>
<li><strong>大型应用通常是客户端+服务端负载均衡搭配使用</strong></li>
</ul>
<h2 id="技术选型"><a href="#技术选型" class="headerlink" title="技术选型"></a>技术选型</h2><p><img src="https://gitee.com/littlefxc/oss/raw/master/images/image-20211021160704789.png" alt="image-20211021160704789"></p>
<p>红色框表示客户端模式，灰色框表示服务端模式。</p>
<p>客户端模式对开发团队更友好，负载均衡策略直接在代码中，易于直接开发自定义的策略，而服务端模式往往在Nginx等接入层网关中，而Nginx还是比较友好的，如果是F5的话，开发团队根本就没有机会好吧，这也往往是服务端模式的负载均衡运维成本高的原因。</p>
<h2 id="深入Ribbon"><a href="#深入Ribbon" class="headerlink" title="深入Ribbon"></a>深入Ribbon</h2><h3 id="负载均衡策略和原理，加载方式，IPing-机制"><a href="#负载均衡策略和原理，加载方式，IPing-机制" class="headerlink" title="负载均衡策略和原理，加载方式，IPing 机制"></a>负载均衡策略和原理，加载方式，IPing 机制</h3><p><img src="https://gitee.com/littlefxc/oss/raw/master/images/5e12e23709f43f6528861210.png"></p>
<p>一个HttpRequest发过来，先被转发到Eureka上。此时Eureka仍然通过服务发现获取了所有服务节点的物理地址，但问题是他不知道该调用哪一个，只好把请求转到了Ribbon手里。</p>
<ul>
<li><p>IPing</p>
<p>IPing是Ribbon的一套healthcheck机制，故名思议，就是要Ping一下目标机器看是否还在线，一般情况下IPing并不会主动向服务节点发起healthcheck请求，Ribbon后台通过静默处理返回true默认表示所有服务节点都处于存活状态（和Eureka集成的时候会检查服节点UP状态）。</p>
<p>IPing 有以下几种方式：</p>
<ul>
<li>DummyPing，默认返回true，即认为所有节点都可用，这也是单独使用Ribbon时的默认模式</li>
<li>NIWSDiscoveryPing，借助Eureka服务发现机制获取节点状态，假如节点状态是UP则认为是可用状态</li>
<li>PingUrl，它会主动向服务节点发起一次http调用，如果对方有响应则认为节点可用</li>
</ul>
<p>第三种方式 PingUrl 比较生猛，会对各个服务节点请求个不停，各个节点有可能扛不住压力，因此除非特殊指定，在和Eureka合作时，一般采用第二种方式。</p>
</li>
<li><p>IRule</p>
<p>这就是Ribbon的组件库了，各种负载均衡策略都继承自IRule接口。所有经过Ribbon的请求都会先请示IRule一把，找到负载均衡策略选定的目标机器，然后再把请求转发过去。</p>
</li>
</ul>
<h3 id="LoadBalanced-原理解析"><a href="#LoadBalanced-原理解析" class="headerlink" title="LoadBalanced 原理解析"></a>LoadBalanced 原理解析</h3><p><img src="https://gitee.com/littlefxc/oss/raw/master/images/5e12e63009550a2029541170.png"></p>
<h4 id="LoadBalanced"><a href="#LoadBalanced" class="headerlink" title="@LoadBalanced"></a>@LoadBalanced</h4><p>这个注解一头挂在<code>RestTemplate</code>上，另一头挂在<code>LoadBalancerAutoConfiguration</code>这个类上。它就像连接两个世界的传送门，将所有顶着「LoadBalanced」注解的RestTemplate类，都传入到<code>LoadBalancerAutoConfiguration</code>中。如果要深挖底层的作用机制，大家可以发现这个注解的定义上还有一个<code>@Qualifier</code>注解。@Qualifier注解搭配@Autowired注解做自动装配，可以通过name属性，将指定的Bean装载到指定位置（即使有两个同样类型的Bean，也可以通过Qualifier定义时声明的name做区分）。这里「LoadBalanced」也是借助Qualifier实现了一个给RestTemplate打标签的功能，凡是被打标的RestTemplate都会被传送到AutoConfig中做进一步改造。</p>
<h4 id="LBAutoConfig"><a href="#LBAutoConfig" class="headerlink" title="LBAutoConfig"></a>LBAutoConfig</h4><p>从前一步中传送过来的RestTemplate，会经过<code>LBAutoConfig</code>的装配，将一系列的<code>Interceptor</code>（拦截器）添加到RestTemplate中。拦截器是类似职责链编程模型的结构，我们常见的ServletFilter，权限控制器等，都是类似的模式。Ribbon拦截器会拦截每个网络请求做一番处理，在这个过程中拦截器会找到对应的LoadBalancer对HTTP请求进行接管，接着LoadBalancer就会找到默认或指定的负载均衡策略来对HTTP请求进行转发。</p>
<h3 id="负载均衡策略介绍"><a href="#负载均衡策略介绍" class="headerlink" title="负载均衡策略介绍"></a>负载均衡策略介绍</h3><p>Ribbon负载均衡的原理是:从EurekaClient类的Bean获取Provider提供者服务列表清单，并且定 期通过IPing类的Bean去判断Provider的可用性。每次RPC到来时，在Provider提供者服务列表中根据 IRule策略类的Bean计算出每次RPC要访问的最终Provider。</p>
<p>Ribbon内部有一个负载均衡器接口<code>ILoadBalance</code>，定义了添加Provider、获取所有的Provider列表、 获取可用的Provider列表等基础的操作。该接口的核心实现类<code>DynamicServerListLoadBalancer</code>会通过 EurekaClient(实现类为DiscoveryClient)获取Provider清单，并且通过<code>IPing</code>实例定期(每10s)向每 个Provider实例发送“ping”，并且根据Provider是否有响应来判断该Provider提供者实例是否可用。 如果该Provider的可用性发生了改变，或者Provider清单中的数量和之前的不一致，则从注册中心更新或者重新拉取Provider服务实例清单。</p>
<p>每次RPC请求到来时，由Ribbon的IRule负载均衡策略接口的某个实现类就来进行负载均衡。主要的负载均衡的策略实现类如下:</p>
<ol>
<li><p>随机策略(RandomRule) </p>
<p>该策略实现类从Provider提供者服务列表中随机选择一个Provider服务实例，作为RPC请求的目标Provider。</p>
</li>
<li><p>线性轮询策略(RoundRobinRule)</p>
<p>RoundRobinRule线性轮询和RandomRule相似，只是每次都取下一个Provider服务器。假设一共有5台Provider服务节点，使用线性轮询策略，第1次取第1台，第2次取第2台，第3次取第3台，以此类推。</p>
</li>
<li><p>响应时间权重策略(WeightedResponseTimeRule)</p>
<p>WeightedResponseTimeRule策略为每一个Provider服务维护一个权重值，其规则简单概况为 Provider服务响应时间越长，其权重就越小。在进行服务器选择时，权重值越小，被选择的机会越少。 WeightedResponseTimeRule继承了RoundRobinRule，开始时每一个Provider都没有权重值，每当RPC 请求过来时，由其父类的轮询算法完成负载均衡方式。该策略类有一个默认、每30秒执行一次的权 重更新定时任务，该定时任务会根据Provider实例的响应时间更新Provider权重列表。后续有RPC过来时，将根据权重值进行负载均衡。</p>
</li>
<li><p>最少连接策略(BestAvailableRule)</p>
<p>在进行服务器选择时，该策略类遍历Provider清单，选取出可用的且连接数最少的一个Provider。 该策略类里面有一个LoadBalancerStats类型的成员变量，会存储所有Provider的运行状况和连接数。 在进行负载均衡计算时，如果选取到的Provider为null，那么会调用线性轮询策略重新选取。</p>
</li>
<li><p>重试策略(RetryRule)</p>
<p>该类会在一定的时限内进行Provider循环重试。RetryRule会在每次选取之后，对选举的Provider进行判断，如果为null或者not alive，会在一定的时限内(如500ms)内会不停的选取和判断。</p>
</li>
<li><p>可用过滤策略(AvailabilityFilteringRule)</p>
<p>该类扩展了线性轮询策略，会先通过默认的线性轮询策略选取一个Provider，再去判断该Provider 是否超时可用，当前连接数是否超过限制，如果都满足要求，则成功返回。</p>
<p>简单来说，AvailabilityFilteringRule将对候选的Provider进行可用性过滤，会先过滤掉多次访问 故障而处于断路器跳闸状态的Provider服务，还会过滤掉并发的连接数超过阈值的Provider服务，然后，对剩余的服务列表进行线性轮询。</p>
</li>
<li><p>区域过滤策略(ZoneAvoidanceRule)</p>
<p>该类扩展了线性轮询策略，除了过滤超时和连接数过多的Provider之外，还会过滤掉不符合要求的Zone区域中的所有节点。</p>
</li>
</ol>
<p>Ribbon实现的负载均衡策略，不止以上7种，还可以实现自定义的策略类。</p>
<h4 id="负载均衡策略配置"><a href="#负载均衡策略配置" class="headerlink" title="负载均衡策略配置"></a>负载均衡策略配置</h4><p>局部微服务负载均衡配置示例如下：</p>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">user-provider:</span></span><br><span class="line">  <span class="attr">ribbon:</span></span><br><span class="line">    <span class="attr">NFLoadBalancerRuleClassName:</span> <span class="string">com.netflix.loadbalancer.RetryRule</span> <span class="comment">#重试+线性轮询</span></span><br><span class="line">  <span class="comment"># NFLoadBalancerRuleClassName: com.netflix.loadbalancer.BestAvailableRule #最少连接策略</span></span><br><span class="line">  <span class="comment"># NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule #随机选择</span></span><br></pre></td></tr></table></figure>

<p>如果要配置全局的、针对所有的Provider都使用的负载均衡策略，可以在配置文件中直接使用 <code>ribbon.NFLoadBalancerRuleClassName</code>配置项进行配置，具体如下:</p>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">ribbon:</span></span><br><span class="line">  <span class="attr">NFLoadBalancerRuleClassName:</span> <span class="string">com.netflix.loadbalancer.RetryRule</span> <span class="comment">#重试+线性轮询</span></span><br><span class="line"><span class="comment"># NFLoadBalancerRuleClassName: com.netflix.loadbalancer.BestAvailableRule #最少连接策略</span></span><br><span class="line"><span class="comment"># NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule #随机选择</span></span><br></pre></td></tr></table></figure>

<h3 id="Ribbon自定义基于哈希一致性负载均衡策略的IRule"><a href="#Ribbon自定义基于哈希一致性负载均衡策略的IRule" class="headerlink" title="Ribbon自定义基于哈希一致性负载均衡策略的IRule"></a>Ribbon自定义基于哈希一致性负载均衡策略的IRule</h3><h4 id="一致性哈希简单介绍"><a href="#一致性哈希简单介绍" class="headerlink" title="一致性哈希简单介绍"></a>一致性哈希简单介绍</h4><p><img src="https://gitee.com/littlefxc/oss/raw/master/images/image-20220211103649256.png" alt="image-20220211103649256"></p>
<p>说明：</p>
<ul>
<li>上图所示有 4 台服务器，均匀分布在一个环上，</li>
<li>提取请求的特征量（可以是请求中的parameter，也可以是整个URL或者请求体中的一个字段），通过某种算法形成摘要，再把摘要通过 hashcode 算法过滤一遍变成一个 int 值，映射到这个环上的某个位置，</li>
<li>然后，<strong>顺时针或者逆时针</strong>去寻找离它最近的一个服务器节点。</li>
<li>通过一个摘要把这个请求定位到一个圆环上，接下来按照固定方向寻找服务器就行了。</li>
<li>假如某个服务节点不可用，那么只需将定位到该节点的请求重新定位到离它最近的节点就好了，其它的请求保持不变，没有任何影响。</li>
</ul>
<h4 id="自定义IRule实现"><a href="#自定义IRule实现" class="headerlink" title="自定义IRule实现"></a>自定义IRule实现</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 基于哈希一致性实现的负载均衡策略</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> fengxuechao</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2022/2/11</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">HashRule</span> <span class="keyword">extends</span> <span class="title">AbstractLoadBalancerRule</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">initWithNiwsConfig</span><span class="params">(IClientConfig iClientConfig)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Server <span class="title">choose</span><span class="params">(Object key)</span> </span>&#123;</span><br><span class="line">        HttpServletRequest request = ((ServletRequestAttributes)</span><br><span class="line">                RequestContextHolder.getRequestAttributes())</span><br><span class="line">                .getRequest();</span><br><span class="line"></span><br><span class="line">        String uri = request.getServletPath() + <span class="string">&quot;?&quot;</span> + request.getQueryString();</span><br><span class="line">        <span class="keyword">return</span> route(uri.hashCode(), getLoadBalancer().getAllServers());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> Server <span class="title">route</span><span class="params">(<span class="keyword">int</span> hashId, List&lt;Server&gt; servers)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (CollectionUtils.isEmpty(servers)) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 这个可以换成更好的算法</span></span><br><span class="line">        TreeMap&lt;Long, Server&gt; serverMap = <span class="keyword">new</span> TreeMap&lt;&gt;();</span><br><span class="line">        servers.forEach(itemServer -&gt; &#123;</span><br><span class="line">            <span class="comment">// 虚化若干个服务节点到环上</span></span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">8</span>; i++) &#123;</span><br><span class="line">                <span class="keyword">long</span> hash = hash(itemServer.getId() + i);</span><br><span class="line">                serverMap.put(hash, itemServer);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">long</span> hash = hash(String.valueOf(hashId));</span><br><span class="line">        SortedMap&lt;Long, Server&gt; sortedMap = serverMap.tailMap(hash);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// request 的 URL 的 hash 值大于任意一个服务器对应的一个 HashKey, 取 servers 中的第一个节点</span></span><br><span class="line">        <span class="keyword">if</span> (sortedMap.isEmpty()) &#123;</span><br><span class="line">            <span class="keyword">return</span> serverMap.firstEntry().getValue();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> sortedMap.get(sortedMap.firstKey());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">long</span> <span class="title">hash</span><span class="params">(String key)</span> </span>&#123;</span><br><span class="line">        MessageDigest md5;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            md5 = MessageDigest.getInstance(<span class="string">&quot;MD5&quot;</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (NoSuchAlgorithmException e) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(e);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">byte</span>[] keyBytes = key.getBytes(StandardCharsets.UTF_8);</span><br><span class="line">        md5.update(keyBytes);</span><br><span class="line">        <span class="keyword">byte</span>[] digest = md5.digest();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">long</span> hashcode = ((<span class="keyword">long</span>) (digest[<span class="number">2</span>] &amp; <span class="number">0xFF</span> &lt;&lt; <span class="number">16</span>))</span><br><span class="line">                | ((<span class="keyword">long</span>) (digest[<span class="number">1</span>] &amp; <span class="number">0xFF</span> &lt;&lt; <span class="number">8</span>))</span><br><span class="line">                | ((<span class="keyword">long</span>) (digest[<span class="number">1</span>] &amp; <span class="number">0xFF</span>));</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> hashcode &amp; <span class="number">0xffffffffL</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/ribbon/" rel="tag"># ribbon</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2021/12/31/docs/%E6%BC%8F%E6%B4%9E%E4%BF%AE%E5%A4%8D/centos7%E4%B8%8Bopenssh%E5%8D%87%E7%BA%A7%E6%96%B9%E6%B3%95%EF%BC%88%E7%BC%96%E8%AF%91%E5%AE%89%E8%A3%85%EF%BC%89/" rel="prev" title="centos7下openssh升级方法（编译安装）">
                  <i class="fa fa-chevron-left"></i> centos7下openssh升级方法（编译安装）
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2022/01/14/docs/JVM/JVM-%E8%99%9A%E6%8B%9F%E6%9C%BA%E6%80%A7%E8%83%BD%E7%9B%91%E6%8E%A7%E6%95%85%E9%9A%9C%E5%A4%84%E7%90%86%E5%B7%A5%E5%85%B7/" rel="next" title="虚拟机性能监控故障处理工具">
                  虚拟机性能监控故障处理工具 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>







<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">一年春又来</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/mist/" class="theme-link" rel="noopener" target="_blank">NexT.Mist</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
<script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script>

  
<script src="/js/local-search.js"></script>






  





</body>
</html>
